import QtQuick 2.15
import QtQuick.Window 2.15
import QtQuick.Controls 2.15
import QtQuick.Layouts 1.15
import PowerCloud 1.0
import "pages"
import "components"

ApplicationWindow {
    id: mainWindow
    visible: true
    visibility: Window.Maximized
    title: "智慧配电云监控系统 v1.0.0"

    // 最小窗口大小
    minimumWidth: 1024
    minimumHeight: 768

    // 背景色
    color: "#f5f5f5"

    // 主布局
    RowLayout {
        anchors.fill: parent
        spacing: 0

        // 左侧导航栏
        Rectangle {
            id: sidebar
            Layout.preferredWidth: 200
            Layout.fillHeight: true
            color: "#2c3e50"

            Column {
                anchors.fill: parent
                anchors.margins: 0
                spacing: 0

                // Logo 区域
                Rectangle {
                    width: parent.width
                    height: 80
                    color: "#1a252f"

                    Column {
                        anchors.centerIn: parent
                        spacing: 5

                        Text {
                            text: "⚡"
                            font.pixelSize: 32
                            color: "#3498db"
                            anchors.horizontalCenter: parent.horizontalCenter
                        }

                        Text {
                            text: "智慧配电云"
                            font.pixelSize: 16
                            font.bold: true
                            color: "white"
                            anchors.horizontalCenter: parent.horizontalCenter
                        }
                    }
                }

                // 导航菜单
                ListView {
                    id: menuListView
                    width: parent.width
                    height: parent.height - 80
                    model: menuModel
                    delegate: menuDelegate
                    currentIndex: 0
                    interactive: false
                }
            }
        }

        // 右侧内容区域
        Rectangle {
            Layout.fillWidth: true
            Layout.fillHeight: true
            color: "#ecf0f1"

            ColumnLayout {
                anchors.fill: parent
                anchors.margins: 15
                spacing: 15

                // 顶部状态栏
                Rectangle {
                    Layout.fillWidth: true
                    Layout.preferredHeight: 60
                    Layout.minimumHeight: 60
                    Layout.maximumHeight: 60
                    color: "white"
                    radius: 8

                    RowLayout {
                        anchors.fill: parent
                        anchors.margins: 15
                        spacing: 20

                        // 系统状态
                        Column {
                            spacing: 5

                            Text {
                                text: "系统状态"
                                font.pixelSize: 12
                                color: "#7f8c8d"
                            }

                            Row {
                                spacing: 5

                                Rectangle {
                                    width: 10
                                    height: 10
                                    radius: 5
                                    color: "#27ae60"
                                    anchors.verticalCenter: parent.verticalCenter

                                    SequentialAnimation on opacity {
                                        running: true
                                        loops: Animation.Infinite
                                        NumberAnimation { to: 0.3; duration: 1000 }
                                        NumberAnimation { to: 1.0; duration: 1000 }
                                    }
                                }

                                Text {
                                    text: "运行中"
                                    font.pixelSize: 14
                                    font.bold: true
                                    color: "#27ae60"
                                }
                            }
                        }

                        Rectangle {
                            width: 1
                            height: 30
                            color: "#bdc3c7"
                        }

                        // 设备统计
                        Column {
                            spacing: 5

                            Text {
                                text: "在线设备"
                                font.pixelSize: 12
                                color: "#7f8c8d"
                            }

                            Text {
                                text: (deviceManager ? deviceManager.onlineCount : 0) + " / " + (deviceManager ? deviceManager.totalCount : 120)
                                font.pixelSize: 14
                                font.bold: true
                                color: "#2c3e50"
                            }
                        }

                        Rectangle {
                            width: 1
                            height: 30
                            color: "#bdc3c7"
                        }

                        // 报警统计
                        Column {
                            spacing: 5

                            Text {
                                text: "报警数量"
                                font.pixelSize: 12
                                color: "#7f8c8d"
                            }

                            Text {
                                text: alarmEngine ? alarmEngine.activeAlarmCount : 0
                                font.pixelSize: 14
                                font.bold: true
                                color: "#e74c3c"
                                
                                // 闪烁动画（当有报警时）
                                SequentialAnimation on opacity {
                                    running: alarmEngine && alarmEngine.activeAlarmCount > 0
                                    loops: Animation.Infinite
                                    NumberAnimation { to: 0.3; duration: 500 }
                                    NumberAnimation { to: 1.0; duration: 500 }
                                }
                            }
                        }

                        // 系统运行时间
                        Column {
                            spacing: 5

                            Text {
                                text: "运行时长"
                                font.pixelSize: 12
                                color: "#7f8c8d"
                            }

                            Text {
                                id: runtimeText
                                text: "00:00:00"
                                font.pixelSize: 14
                                font.bold: true
                                color: "#2c3e50"

                                property int totalSeconds: 0

                                Timer {
                                    interval: 1000
                                    running: true
                                    repeat: true
                                    onTriggered: {
                                        runtimeText.totalSeconds++
                                        var hours = Math.floor(runtimeText.totalSeconds / 3600)
                                        var minutes = Math.floor((runtimeText.totalSeconds % 3600) / 60)
                                        var seconds = runtimeText.totalSeconds % 60
                                        
                                        var hoursStr = hours < 10 ? "0" + hours : hours
                                        var minutesStr = minutes < 10 ? "0" + minutes : minutes
                                        var secondsStr = seconds < 10 ? "0" + seconds : seconds
                                        
                                        runtimeText.text = hoursStr + ":" + minutesStr + ":" + secondsStr
                                    }
                                }
                            }
                        }

                        Rectangle {
                            width: 1
                            height: 30
                            color: "#bdc3c7"
                        }

                        Item {
                            Layout.fillWidth: true
                        }

                        // 当前时间
                        Column {
                            spacing: 5

                            Text {
                                text: "当前时间"
                                font.pixelSize: 12
                                color: "#7f8c8d"
                            }

                            Text {
                                id: timeText
                                text: Qt.formatDateTime(new Date(), "yyyy-MM-dd hh:mm:ss")
                                font.pixelSize: 14
                                font.bold: true
                                color: "#2c3e50"

                                Timer {
                                    interval: 1000
                                    running: true
                                    repeat: true
                                    onTriggered: {
                                        timeText.text = Qt.formatDateTime(new Date(), "yyyy-MM-dd hh:mm:ss")
                                    }
                                }
                            }
                        }
                    }
                }

                // 主内容区域 - 使用 StackView 进行页面切换
                Rectangle {
                    Layout.fillWidth: true
                    Layout.fillHeight: true
                    Layout.minimumHeight: 400
                    color: "transparent"
                    radius: 8
                    clip: true  // 裁剪溢出内容，防止动画覆盖其他区域

                    StackView {
                        id: stackView
                        anchors.fill: parent
                        initialItem: dashboardPage

                        // 页面切换动画 - 使用平移而非透明度，避免覆盖问题
                        pushEnter: Transition {
                            PropertyAnimation {
                                property: "x"
                                from: stackView.width
                                to: 0
                                duration: 200
                                easing.type: Easing.OutCubic
                            }
                        }

                        pushExit: Transition {
                            PropertyAnimation {
                                property: "x"
                                from: 0
                                to: -stackView.width * 0.3
                                duration: 200
                                easing.type: Easing.OutCubic
                            }
                        }

                        popEnter: Transition {
                            PropertyAnimation {
                                property: "x"
                                from: -stackView.width * 0.3
                                to: 0
                                duration: 200
                                easing.type: Easing.OutCubic
                            }
                        }

                        popExit: Transition {
                            PropertyAnimation {
                                property: "x"
                                from: 0
                                to: stackView.width
                                duration: 200
                                easing.type: Easing.OutCubic
                            }
                        }
                    }
                }
            }
        }
    }

    // 菜单数据模型
    ListModel {
        id: menuModel

        ListElement {
            icon: "📊"
            name: "总览"
            page: "dashboard"
        }

        ListElement {
            icon: "📋"
            name: "仪表列表"
            page: "meterlist"
        }

        ListElement {
            icon: "📈"
            name: "历史查询"
            page: "history"
        }

        ListElement {
            icon: "⚠️"
            name: "报警记录"
            page: "alarm"
        }

        ListElement {
            icon: "⚙️"
            name: "系统设置"
            page: "settings"
        }

        ListElement {
            icon: "ℹ️"
            name: "关于"
            page: "about"
        }
    }

    // 菜单项委托
    Component {
        id: menuDelegate

        Rectangle {
            id: menuItem
            width: menuListView.width
            height: 50
            color: menuListView.currentIndex === index ? "#34495e" : "transparent"

            MouseArea {
                anchors.fill: parent
                hoverEnabled: true
                cursorShape: Qt.PointingHandCursor

                onEntered: {
                    if (menuListView.currentIndex !== index) {
                        menuItem.color = "#2c3e50"
                    }
                }

                onExited: {
                    if (menuListView.currentIndex !== index) {
                        menuItem.color = "transparent"
                    }
                }

                onClicked: {
                    menuListView.currentIndex = index
                    switchPage(model.page)
                }
            }

            Row {
                anchors.verticalCenter: parent.verticalCenter
                anchors.left: parent.left
                anchors.leftMargin: 20
                spacing: 15

                Text {
                    text: model.icon
                    font.pixelSize: 20
                    anchors.verticalCenter: parent.verticalCenter
                }

                Text {
                    text: model.name
                    font.pixelSize: 14
                    color: "white"
                    anchors.verticalCenter: parent.verticalCenter
                }
            }

            // 选中指示器
            Rectangle {
                width: 4
                height: parent.height
                color: "#3498db"
                visible: menuListView.currentIndex === index
                anchors.right: parent.right
            }
        }
    }

    // 页面组件
    Component {
        id: dashboardPage
        DashboardPage {}
    }

    Component {
        id: meterListPage
        MeterListPage {}
    }

    Component {
        id: meterDetailPage
        MeterDetailPage {
            meterId: 1
        }
    }

    Component {
        id: historyPage
        HistoryPage {}
    }

    Component {
        id: aboutPage
        AboutPage {}
    }

    Component {
        id: settingsPage
        SettingsPage {}
    }

    Component {
        id: alarmRecordPage
        AlarmRecordPage {}
    }

    Component {
        id: welcomePage
        
        Rectangle {
            color: "white"
            
            ColumnLayout {
                anchors.centerIn: parent
                spacing: 20

                Text {
                    text: "⚡"
                    font.pixelSize: 80
                    color: "#3498db"
                    Layout.alignment: Qt.AlignHCenter
                }

                Text {
                    text: "欢迎使用智慧配电云监控系统"
                    font.pixelSize: 24
                    font.bold: true
                    color: "#2c3e50"
                    Layout.alignment: Qt.AlignHCenter
                }

                Text {
                    text: "版本 1.0.0"
                    font.pixelSize: 14
                    color: "#7f8c8d"
                    Layout.alignment: Qt.AlignHCenter
                }

                Rectangle {
                    width: 400
                    height: 1
                    color: "#bdc3c7"
                    Layout.alignment: Qt.AlignHCenter
                    Layout.topMargin: 20
                    Layout.bottomMargin: 20
                }

                Text {
                    text: "监控 3 个配电室，共 120 块 PM2220 电表"
                    font.pixelSize: 14
                    color: "#95a5a6"
                    Layout.alignment: Qt.AlignHCenter
                }

                Button {
                    text: "进入系统"
                    font.pixelSize: 14
                    Layout.alignment: Qt.AlignHCenter
                    Layout.topMargin: 20
                    onClicked: {
                        switchPage("dashboard")
                    }
                }
            }
        }
    }

    // 报警弹窗
    AlarmDialog {
        id: alarmDialog
        parent: Overlay.overlay
        autoClose: true
        autoCloseDelay: 10000  // 10秒自动关闭
    }

    // 页面切换函数
    function switchPage(pageName) {
        console.log("切换到页面:", pageName)
        
        var menuIndex = -1
        
        switch(pageName) {
            case "dashboard":
                stackView.replace(dashboardPage)
                menuIndex = 0
                break
            case "meterlist":
                stackView.replace(meterListPage)
                menuIndex = 1
                break
            case "history":
                stackView.replace(historyPage)
                menuIndex = 2
                break
            case "alarm":
                stackView.replace(alarmRecordPage)
                menuIndex = 3
                break
            case "settings":
                stackView.replace(settingsPage)
                menuIndex = 4
                break
            case "about":
                stackView.replace(aboutPage)
                menuIndex = 5
                break
            default:
                console.log("未知页面:", pageName)
        }
        
        // 自动更新菜单选中状态
        if (menuIndex >= 0) {
            menuListView.currentIndex = menuIndex
        }
    }
    
    // 设置菜单选中索引（供外部调用）
    function setMenuIndex(index) {
        menuListView.currentIndex = index
    }
    
    // 打开电表详情页（全局函数，供子页面调用）
    function openMeterDetail(meterId) {
        console.log("main.qml: openMeterDetail 被调用, meterId=", meterId)
        
        // 简单直接的方式：立即 push，不做额外处理
        try {
            console.log("main.qml: 直接 push 详情页...")
            var detailPage = stackView.push("qrc:/pages/MeterDetailPage.qml", { "meterId": meterId })
            console.log("main.qml: push 完成, detailPage=", detailPage)
        } catch (e) {
            console.error("main.qml: push 出错:", e)
        }
    }
    
    // 返回上一页（全局函数，供子页面调用）
    function goBack() {
        console.log("main.qml: goBack 被调用")
        console.log("main.qml: stackView.depth=", stackView.depth)
        
        try {
            if (stackView.depth > 1) {
                stackView.pop()
                console.log("main.qml: pop 完成")
            } else {
                console.warn("main.qml: 已经在最顶层，无法返回")
            }
        } catch (e) {
            console.error("main.qml: pop 出错:", e)
        }
    }
    
    // 通用页面导航函数（支持传递参数）
    function navigateTo(pageName, params) {
        console.log("main.qml: navigateTo 被调用, pageName=", pageName, ", params=", JSON.stringify(params || {}))
        
        try {
            var pageUrl = ""
            var menuIndex = -1
            
            // 根据页面名称确定URL和菜单索引
            switch(pageName) {
                case "DashboardPage":
                case "dashboard":
                    pageUrl = "qrc:/pages/DashboardPage.qml"
                    menuIndex = 0
                    break
                case "MeterListPage":
                case "meterlist":
                    pageUrl = "qrc:/pages/MeterListPage.qml"
                    menuIndex = 1
                    break
                case "HistoryPage":
                case "history":
                    pageUrl = "qrc:/pages/HistoryPage.qml"
                    menuIndex = 2
                    break
                case "AlarmRecordPage":
                case "alarm":
                    pageUrl = "qrc:/pages/AlarmRecordPage.qml"
                    menuIndex = 3
                    break
                case "SettingsPage":
                case "settings":
                    pageUrl = "qrc:/pages/SettingsPage.qml"
                    menuIndex = 4
                    break
                case "AboutPage":
                case "about":
                    pageUrl = "qrc:/pages/AboutPage.qml"
                    menuIndex = 5
                    break
                case "MeterDetailPage":
                    // 详情页不在主菜单中，使用push
                    pageUrl = "qrc:/pages/MeterDetailPage.qml"
                    break
                default:
                    console.warn("main.qml: 未知页面:", pageName)
                    return
            }
            
            // 如果有参数，使用push推入新页面；否则使用replace替换
            if (params && Object.keys(params).length > 0) {
                stackView.push(pageUrl, params)
                // 即使有参数，如果是主菜单页面，也要更新菜单选中状态
                if (menuIndex >= 0) {
                    menuListView.currentIndex = menuIndex
                }
            } else {
                // 主页面使用replace，避免堆栈过深
                if (menuIndex >= 0) {
                    stackView.replace(pageUrl)
                    menuListView.currentIndex = menuIndex
                } else {
                    stackView.push(pageUrl)
                }
            }
            
            console.log("main.qml: navigateTo 完成, 菜单索引=", menuIndex)
        } catch (e) {
            console.error("main.qml: navigateTo 出错:", e)
        }
    }

    // 显示报警弹窗
    function showAlarmNotification(alarmEvent) {
        alarmDialog.showAlarm(alarmEvent)
    }

    // 连接报警引擎信号
    Connections {
        target: alarmEngine
        
        function onAlarmTriggered(event) {
            console.log("报警触发:", event.typeName, event.meterName)
            // 显示报警弹窗
            showAlarmNotification(event)
        }
    }

    // 组件加载完成
    Component.onCompleted: {
        console.log("主界面加载完成")
        console.log("DeviceManager:", deviceManager)
        console.log("MeterModel:", meterModel)
        console.log("AlarmEngine:", alarmEngine)
        console.log("AlarmModel:", alarmModel)
    }
}

